import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { useRouterStore } from '@/store'

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const routerStore = useRouterStore()

  /* 更新菜单的Index */
  routerStore.currentRouteInfo = to
  routerStore.currentMenuActiveIndex = to.meta.indexM

  // 更新标签历史记录列表
  if (to.path !== '/workbench') {
    let hNameList = routerStore.tagHistoryList.map(item => {
      return item.name
    })

    if (hNameList.indexOf(to.name) === -1)
      routerStore.tagHistoryList.push({
        path: to.path,
        name: to.name,
        isHover: false,
        isActive: false,
        title: to.meta.title
      })

    // 更新当前标签激活状态
    routerStore.tagHistoryList.forEach(item => {
      item.isActive = false
      if (item.name == to.name) item.isActive = true
    })
  } else {
    routerStore.tagHistoryList.forEach(item => {
      item.isActive = false
    })
  }

  next()
})

export default router
